const modal = require('./modal')
const shortid = require('shortid')
const schema = modal.schema
const config = require('./config')
const util = require('./util')

Parse.Cloud.job('generateAdmin', async (request) => {
  const users = []
  for (let i = 0; i < 10; i++) {
    const user = new Parse.User()
    if (i === 0) {
      user.set('username', 'admin')
    } else {
      user.set('username', `admin${i}`)
    }
    user.set('password', 'iwoor@168')
    users.push(user)
  }
  try {
    await Parse.Object.saveAll(users)
  } catch (err) {
    console.log(err)
  }
  console.log('done')
})

Parse.Cloud.job('generateFirstUser', async (request) => {
  const wechat = 'wechat1'
  // 创建用户
  const user = modal.user()
  const group = schema.group()
  const currentUser = await user.signUp({
    username: wechat,
    password: '123456'
  })
  const member = schema.member()
  const currentMember = await member.save({
    name: wechat,
    mobile: 13129376589,
    wechat,
    qq: 987653748,
    shareRate: config.shareRate.level1.self,
    level: 1,
    inviteCode: shortid.generate(),
    status: 0,
    user: currentUser,
    parent: null,
    sheet: util.generateSheet()
  })
  const groupCode = new Date().getTime() + parseInt(Math.random() * 100, 10)
  await group.save({
    name: `群${groupCode}`,
    member: currentMember,
    groupCode,
    status: 0
  })
  console.log('generate success')
})
Parse.Cloud.job('generateRoles', async (request) => {
  const roleACL = new Parse.ACL()
  roleACL.setPublicReadAccess(true)
  roleACL.setPublicWriteAccess(true)
  const querySuper = modal.user().query()
  querySuper.equalTo('username', 'admin')
  const findSuper = querySuper.first()
  const queryAdmin = modal.user().query()
  const usernames = []
  for (let i = 1; i < 10; i++) {
    usernames.push(`admin${i}`)
  }
  queryAdmin.containedIn('username', usernames)
  const findAdmin = queryAdmin.find()
  try {
    const superUser = await findSuper
    const admins = await findAdmin
    const superRole = new Parse.Role('super', roleACL)
    const administratorRole = new Parse.Role('administrator', roleACL)
    const superRoleRelation = superRole.relation('users')
    const adminRoleRelation = administratorRole.relation('users')
    superRoleRelation.add(superUser)
    adminRoleRelation.add(admins)
    await Parse.Object.saveAll([superRole, administratorRole])
  } catch (err) {
    console.log(err)
  }
})

